import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:like_button/like_button.dart';
import 'package:live_music/components/feedback/PageFeedBack.dart';
import 'package:live_music/components/ui/tag.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/event/commentEvent.dart';
import 'package:live_music/event/momonEvent.dart';
import 'package:live_music/models/comment_detail_model.dart';
import 'package:live_music/models/moment_detail_model.dart';
import 'package:live_music/models/moment_list_model.dart';
import 'package:live_music/models/topic_detail_model.dart';
import 'package:live_music/pages/detail/widget/moment_comment_detail.dart';
import 'package:live_music/pages/detail/widget/moment_file_detail.dart';
import 'package:live_music/pages/detail/widget/moment_swiper_detail.dart';
import 'package:live_music/pages/detail/widget/moment_title_detail.dart';
import 'package:live_music/pages/detail/widget/moment_video_detail.dart';
import 'package:live_music/pages/publish/widget/frinend_list_select_publish.dart';
import 'package:live_music/pages/topic/topic_detail.dart';
import 'package:live_music/services/commentService.dart';
import 'package:live_music/services/indexService.dart';
import 'package:live_music/services/momentService.dart';
import 'package:live_music/services/operationServiece.dart';
import 'package:live_music/services/topicService.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/contentParse.dart';
import 'package:live_music/utils/eventBusUtils.dart';
import 'package:live_music/utils/sp_utils.dart';
import 'package:live_music/utils/toast_utils.dart';
import 'package:live_music/utils/util.dart';

class MomentDetailPage extends StatefulWidget {
  int id;
  MomentDetailPage({Key key, this.id}) : super(key: key);

  @override
  _MomentDetailPageState createState() => _MomentDetailPageState();
}

class _MomentDetailPageState extends State<MomentDetailPage>
    with WidgetsBindingObserver {
  MomentDetailModel momentDetailData = MomentDetailModel();
  TextEditingController _commentEditController;
  CommentDetailModel parentComment;
  bool isShowkeyborad = false;
  bool disabledPublish = true;
  FocusNode _focusNode = FocusNode();
  dynamic id;
  void initState() {
    super.initState();
    setState(() {
      id=widget.id!=null?widget.id:Get.parameters['id'];
    });
    WidgetsBinding.instance?.addObserver(this);
    _commentEditController = TextEditingController();
    EventBusUtils.getInstance().on<SelectFriendPublishEvent>().listen((event) {
      setState(() {
        _commentEditController.text =
            _commentEditController.text + event.name + " ";
      });
    });
    EventBusUtils.getInstance().on<CommentEventPublish>().listen((event) {
      if (parentComment == null) {
        setState(() {
          parentComment = event.parentComment;
        });
        return;
      }
      if (event.parentComment.id == parentComment.id) {
        setState(() {
          parentComment = null;
        });
      } else {
        setState(() {
          parentComment = event.parentComment;
        });
      }
    });
    initData();
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      setState(() {
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          //关闭键盘
          isShowkeyborad = false;
        } else {
          //显示键盘
          isShowkeyborad = true;
        }
      });
    });
  }

  initData() async {
    await loadMomentDetail();
  }

  loadMomentDetail() async {
    try {
      Map<String, dynamic> data = {"momentId": id};
      Map<String, dynamic> detailData =
          await MomentService.queryMomentDetail(data);
      MomentDetailModel momentDetail =
          MomentDetailModel.fromJson(detailData['body']);
      setState(() {
        momentDetailData = momentDetail;
      });
    } catch (e) {
      ToastUtils.showToast(e['retdesc'] != null ? e['retdesc'] : '出现异常');
      Get.back();
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
        appBar: PreferredSize(
            preferredSize: Size.fromHeight(55),
            child: AppBar(
              elevation: 0.0,
              centerTitle: true,
              title: Center(
                child: MomentTitleDetail(
                    momentDetailData: momentDetailData,
                    addFollowed: (follow) {
                      setState(() {
                        momentDetailData.hasFollowed = follow;
                      });
                    }),
              ),
              automaticallyImplyLeading: false,
              backgroundColor: Colors.white,
            )),
        body: Container(
            height: MediaQuery.of(context).size.height,
            width: screenWidth,
            child: Stack(children: [
              Container(
                color: Colors.white,
                child: MainContent(
                  item: momentDetailData,
                ),
              ),
              Positioned(
                  bottom: 0,
                  left: 0,
                  child: Container(
                    width: screenWidth,
                    height: isShowkeyborad || _commentEditController.text != ""
                        ? 100
                        : 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                    ),
                    child: Column(
                      children: [
                        Divider(
                          height: 1,
                          color: Colors.black12,
                        ),
                        Expanded(
                            child: Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                  flex: 1,
                                  child: Container(
                                    alignment: Alignment.topLeft,
                                    padding:
                                        EdgeInsets.only(left: 10, right: 10),
                                    margin: EdgeInsets.only(
                                        left: 10, right: 6, top: 4, bottom: 4),
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(20),
                                        color: Colors.grey[100]),
                                    child: TextField(
                                      controller: _commentEditController,
                                      cursorColor: Colors.redAccent,
                                      focusNode: _focusNode,
                                      keyboardType: TextInputType.multiline,
                                      maxLines: isShowkeyborad ||
                                              _commentEditController.text != ""
                                          ? 20
                                          : 1,
                                      minLines: 1,
                                      style: TextStyle(
                                          color: Colors.black, fontSize: 11),
                                      decoration: InputDecoration(
                                          // border: OutlineInputBorder(),
                                          border: InputBorder.none,
                                          hintText: parentComment != null
                                              ? '回复' +
                                                  parentComment.userName +
                                                  '：'
                                              : '写评论...',
                                          hintStyle: TextStyle(
                                              color: Colors.grey[600])),
                                    ),
                                  )),
                              isShowkeyborad ||
                                      _commentEditController.text != ""
                                  ? InkWell(
                                      child: Container(
                                        margin: EdgeInsets.only(left: 10),
                                        alignment: Alignment.center,
                                        child: Image.asset(
                                          'assets/images/icons/publish_at.png',
                                          width: 20,
                                          height: 20,
                                        ),
                                      ),
                                      onTap: showBottomFriendList,
                                    )
                                  : Container(),
                              isShowkeyborad ||
                                      _commentEditController.text != ""
                                  ? Container()
                                  : Container(
                                      margin: EdgeInsets.only(
                                          left: 10,
                                          right:
                                              momentDetailData.type == "VIDEO"
                                                  ? 0
                                                  : 10),
                                      alignment: Alignment.center,
                                      child: Row(
                                        children: [
                                          LikeButton(
                                              isLiked:
                                                  momentDetailData.hasLiked,
                                              onTap: (isLiked) {
                                                return onTapLikeButton(
                                                    !isLiked);
                                              },
                                              size: 20,
                                              circleColor: CircleColor(
                                                  start: ColorRes.color_3,
                                                  end: ColorRes.color_3),
                                              likeBuilder: (isLike) {
                                                return isLike == true
                                                    ? Image.asset(
                                                        'assets/images/common/red_heart.webp')
                                                    : Icon(
                                                        Icons
                                                            .favorite_border_outlined,
                                                        size: 20,
                                                        color:
                                                            WcaoTheme.secondary,
                                                      );
                                              },
                                              bubblesColor: const BubblesColor(
                                                dotPrimaryColor:
                                                    ColorRes.color_3,
                                                dotSecondaryColor:
                                                    ColorRes.color_3,
                                                dotThirdColor: ColorRes.color_3,
                                                dotLastColor: ColorRes.color_3,
                                              )),
                                          Text(
                                            momentDetailData.likeCount
                                                .toString(),
                                            style: TextStyle(
                                                color: WcaoTheme.secondary),
                                          ),
                                        ],
                                      )),
                              momentDetailData.type == "VIDEO" &&
                                      !isShowkeyborad &&
                                      _commentEditController.text == "" &&
                                      momentDetailData.repostedMoment == null
                                  ? InkWell(
                                      child: Container(
                                          margin: EdgeInsets.only(
                                              left: 10, right: 10),
                                          alignment: Alignment.center,
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              LikeButton(
                                                  isLiked: momentDetailData
                                                      .video.hasCollected,
                                                  onTap: (isLiked) {
                                                    return onTapCollectButton(
                                                        !isLiked);
                                                  },
                                                  size: 20,
                                                  circleColor: CircleColor(
                                                      start: ColorRes.color_4,
                                                      end: ColorRes.color_4),
                                                  likeBuilder: (isLike) {
                                                    return isLike == true
                                                        ? Image.asset(
                                                            'assets/images/icons/has_collect.png')
                                                        : Image.asset(
                                                            'assets/images/icons/detail_collect.png',
                                                            color: WcaoTheme
                                                                .secondary,
                                                          );
                                                  },
                                                  bubblesColor:
                                                      const BubblesColor(
                                                    dotPrimaryColor:
                                                        ColorRes.color_4,
                                                    dotSecondaryColor:
                                                        ColorRes.color_4,
                                                    dotThirdColor:
                                                        ColorRes.color_4,
                                                    dotLastColor:
                                                        ColorRes.color_4,
                                                  )),
                                              Text(
                                                momentDetailData
                                                    .video.collectCount
                                                    .toString(),
                                                style: TextStyle(fontSize: 12),
                                              )
                                            ],
                                          )),
                                      onTap: publishComment,
                                    )
                                  : Container(),
                              isShowkeyborad ||
                                      _commentEditController.text != ""
                                  ? Container(
                                      height: 30,
                                      width: 60,
                                      margin:
                                          EdgeInsets.only(left: 10, right: 10),
                                      alignment: Alignment.center,
                                      child: ElevatedButton(
                                          style: ButtonStyle(
                                              shape: MaterialStateProperty.all(
                                                  RoundedRectangleBorder(
                                                      borderRadius:
                                                          BorderRadius.circular(
                                                              20))),
                                              backgroundColor:
                                                  MaterialStateProperty.all(
                                                Colors.redAccent,
                                              )),
                                          onPressed: disabledPublish
                                              ? publishComment
                                              : null,
                                          child: const Center(
                                            child: Text(
                                              '发送',
                                              style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 12,
                                                  fontWeight: FontWeight.w500),
                                            ),
                                          )))
                                  : Container(),
                            ],
                          ),
                        ))
                      ],
                    ),
                  ))
            ])));
  }

  //展示好友
  void showBottomFriendList() {
    showModalBottomSheet(
        backgroundColor: Colors.white,
        context: context,
        isScrollControlled: true, //可滚动 解除showModalBottomSheet最大显示屏幕一半的限制
        shape: RoundedRectangleBorder(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        builder: (context) {
          return Container(
              constraints: BoxConstraints(
                  minHeight: MediaQuery.of(context).size.height -
                      kToolbarHeight, //设置最小高度（必要）
                  maxHeight: MediaQuery.of(context).size.height
                  // -
                  //     kToolbarHeight, //设置最大高度（必要）
                  ),
              child: FriendListSelectPublishIndexPage());
        });
  }

  publishComment() async {
    EasyLoading.show(status: '发送中...');
    try {
      setState(() {
        disabledPublish = false;
      });
      Map<String, dynamic> data = {
        "momentId": momentDetailData.id,
        "content": _commentEditController.text,
        "parentId": parentComment != null ? parentComment.id : 0,
        "replyToId": 0
      };
      Map<String, dynamic> result = await CommentService.publishComment(data);
      CommentDetailModel commentDetail;
      if (parentComment == null) {
        Map<String, dynamic> param = {
          "commentId": result['body'],
        };
        Map<String, dynamic> commentResult =
            await CommentService.getCommentDetail(param);
        commentDetail = CommentDetailModel.fromJson(commentResult['body']);
      }
      EventBusUtils.getInstance().fire(AfterPublishComment(
          commentDetail, parentComment != null ? parentComment.id : 0));
      setState(() {
        momentDetailData.commentCount++;
        parentComment = null;
        _commentEditController.text = "";
        disabledPublish = true;
        _focusNode.unfocus();
      });
      ToastUtils.showToast("发送成功");
      EasyLoading.dismiss(animation: true);
    } catch (e) {
      setState(() {
        disabledPublish = true;
      });
      EasyLoading.showError(e['retdesc'] != null ? e['retdesc'] : '发送失败');
      EasyLoading.dismiss(animation: true);
    }
  }

  Future<bool> onTapCollectButton(bool isLiked) async {
    momentDetailData.video.hasCollected = isLiked;
    if (isLiked) {
      momentDetailData.video.collectCount++;
    } else {
      momentDetailData.video.collectCount--;
    }
    Map<String, dynamic> data = {
      "targetId": momentDetailData.video.id,
      "targetType": 'VIDEO',
    };
    if (isLiked) {
      await OperationServiece.collect(data);
    } else {
      await OperationServiece.cancelCollect(data);
    }
    setState(() {
      momentDetailData = momentDetailData;
    });
    return isLiked;
  }

  Future<bool> onTapLikeButton(bool isLiked) async {
    momentDetailData.hasLiked = isLiked;
    if (isLiked) {
      momentDetailData.likeCount++;
    } else {
      momentDetailData.likeCount--;
    }
    Map<String, dynamic> data = {
      "targetId": momentDetailData.id,
      "targetType": 'MOMENT',
    };
    if (isLiked) {
      await OperationServiece.like(data);
    } else {
      await OperationServiece.cancelLike(data);
    }
    setState(() {
      momentDetailData = momentDetailData;
    });
    return isLiked;
  }
}

class MainContent extends StatelessWidget {
  MainContent({Key key, this.item}) : super(key: key);
  MomentDetailModel item;
  final ScrollController controller = ScrollController();
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      controller: controller,
      shrinkWrap: true,
      itemCount: 2,
      itemBuilder: (BuildContext context, int index) {
        if (index == 0) {
          return _momentTypShow(item);
        } else {
          return Article(
            item: item,
          );
        }
      },
    );
  }
}

Widget _momentTypShow(MomentDetailModel item) {
  Widget _momentTypeWidget;
  if (item.repostedMoment != null) {
    return _buildrepostedMoment(item);
  }
  switch (item.type) {
    case "TEXT":
      _momentTypeWidget = Container();
      break;
    case "VIDEO":
      _momentTypeWidget =
          MomentVideoDetail(momentId: item.id, videoItem: item.video);
      break;
    case "IMAGE":
      _momentTypeWidget =
          MomentTopSwiperDetail(momentId: item.id, imageList: item.imageList);
      break;
    case "FILE":
      _momentTypeWidget =
          MomentFileDetail(momentId: item.id, fileItem: item.file);
      break;
  }
  return _momentTypeWidget;
}

_buildrepostedMoment(MomentDetailModel item) {
  return InkWell(
      onTap: () => {},
      child: Container(
          decoration: BoxDecoration(
              color: Colors.grey[200], borderRadius: BorderRadius.circular(8)),
          padding: EdgeInsets.all(8),
          margin: EdgeInsets.only(top: 10, bottom: 6, left: 16, right: 16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text("@" + item.repostedMoment.userName,
                      style: TextStyle(
                        color: Colors.blueAccent,
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      )),
                  Text(":",
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      )),
                ],
              ),
              item.repostedMoment.type == "VIDEO"
                  ? Container(
                      alignment: Alignment.centerLeft,
                      margin: EdgeInsets.only(top: 8),
                      child: Text(
                        item.repostedMoment.video.title,
                        style: TextStyle(fontSize: 14),
                      ))
                  : Container(),
              Container(
                alignment: Alignment.centerLeft,
                margin: EdgeInsets.symmetric(vertical: 10),
                child: _momentTypShow(item.repostedMoment),
              ),
              item.repostedMoment.type == "TEXT"
                  ? Container(
                      alignment: Alignment.centerLeft,
                      margin: EdgeInsets.only(top: 8),
                      child: FormattedText(
                        item.repostedMoment.textContent,
                        style: TextStyle(
                          color: WcaoTheme.base,
                        ),
                      ),
                    )
                  : Container(),
            ],
          )));
}

class Article extends StatelessWidget {
  const Article({Key key, this.item}) : super(key: key);
  final MomentDetailModel item;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          item.type == "VIDEO" && item.repostedMoment == null
              ? Text(
                  item.video.title,
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 14,
                    color: Colors.black87,
                  ),
                )
              : Container(),
          Container(
              child: FormattedText(
            item.textContent,
            style: TextStyle(
              fontSize: 13,
              color: Colors.black87,
              letterSpacing: 1,
              fontWeight: FontWeight.w500,
              height: 1.8,
            ),
          )),
          // item.topicList != null
          //     ? Container(
          //         margin: const EdgeInsets.only(top: 12),
          //         child: Wrap(
          //             spacing: 12,
          //             runSpacing: 6,
          //             children: item.topicList.map((e) {
          //               return InkWell(
          //                 onTap: () async {
          //                   Map<String, dynamic> topicData =
          //                       await TopicService.getTopicDetail(
          //                           {"name": e.name});
          //                   TopicDetailModel topicItem =
          //                       TopicDetailModel.fromJson(topicData['body']);
          //                   Get.to(TopicDetailPage(topicItem: topicItem));
          //                 },
          //                 child: Container(
          //                     height: 30,
          //                     decoration: BoxDecoration(
          //                         borderRadius: BorderRadius.circular(15)),
          //                     child: RaisedButton.icon(
          //                       shape: RoundedRectangleBorder(
          //                           borderRadius: BorderRadius.circular(15)),
          //                       icon: Image.asset(
          //                         'assets/images/icons/' +
          //                             "moment_detail_topic.png",
          //                         width: 16,
          //                         height: 16,
          //                       ),
          //                       // Icon(
          //                       //             Icons.all_inclusive,
          //                       //             color: Colors.blue,
          //                       //             size: 12,
          //                       //           ),
          //                       label: Text(
          //                         e.name,
          //                         style: TextStyle(
          //                             color: Colors.orange, fontSize: 12),
          //                       ),
          //                       disabledColor: Colors.orange[50],
          //                     )),
          //               );
          //             }).toList()),
          //       )
          //     : Container(),
          item.tagList != null
              ? Container(
                  margin: const EdgeInsets.only(top: 12),
                  child: Wrap(
                      spacing: 12,
                      runSpacing: 6,
                      children: item.tagList.map((e) {
                        return Tag(
                          e.name,
                          borderRadius: BorderRadius.circular(24),
                          fontSize: 12,
                          padding: const EdgeInsets.only(
                            top: 2,
                            bottom: 2,
                            left: 8,
                            right: 8,
                          ),
                          color: Colors.pink[300],
                          backgroundColor: Colors.pink[50],
                        );
                      }).toList()),
                )
              : Container(),
          Container(
            height: 40,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  getDateTime(item.createTime),
                  style: TextStyle(fontSize: 11, color: Colors.grey[600]),
                ),
                Container(
                    // height: 24,
                    // padding: EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                    // decoration: BoxDecoration(
                    //     borderRadius: BorderRadius.circular(12),
                    //     border: Border.all(color: Colors.grey, width: 0.2)),
                    // child: Row(
                    //   children: [
                    //     Icon(
                    //       Icons.sentiment_dissatisfied,
                    //       size: 15,
                    //     ),
                    //     Text(
                    //       ' 不喜欢',
                    //       style: TextStyle(fontSize: 11),
                    //     )
                    //   ],
                    // ),
                    )
              ],
            ),
          ),
          Container(
            height: 0.2,
            decoration: BoxDecoration(color: Colors.grey),
            margin: EdgeInsets.symmetric(vertical: 8),
          ),
          SizedBox(
            height: 10,
          ),
          MomentCommentDetail(momentDetailData: item),
          SizedBox(
            height: 30,
          ),
        ],
      ),
    );
  }
}
